<template>
  <div :id="chart.id" />
</template>

<script>
export default {
  name: "G2Pie",
  props: {
    chart: {
      type: Object,
      default() {
        return {
          id: "p1",
          data: [
            { type: "评估中", percent: 0.23 },
            { type: "设计中", percent: 0.28 },
            { type: "正在开发", percent: 0.3 },
            { type: "已上线", percent: 0.19 }
          ]
        };
      }
    }
  },
  data() {
    return {};
  },
  mounted() {
    const data = this.chart.data;
    const container = this.chart.id;
    let sum = 500;
    let ds = new DataSet();
    let dv = ds.createView().source(data);
    dv.transform({
      type: "map",
      callback: function callback(row) {
        row.value = parseInt(sum * row.percent);
        return row;
      }
    });
    let chart = new G2.Chart({
      container,
      forceFit: true,
      height: 300,
      padding: "auto"
    });
    chart.source(dv);
    chart.tooltip(false);
    chart.legend({
      position: "right-center",
      offsetX: -100
    });
    chart.coord("theta", {
      radius: 0.75,
      innerRadius: 0.6
    });
    chart
      .intervalStack()
      .position("percent")
      .color("type", ["#0a7aca", "#0a9afe", "#4cb9ff", "#8ed1ff"])
      .opacity(1)
      .label("percent", {
        offset: -18,
        textStyle: {
          fill: "white",
          fontSize: 12,
          shadowBlur: 2,
          shadowColor: "rgba(0, 0, 0, .45)"
        },
        rotate: 0,
        autoRotate: false,
        formatter: function formatter(text, item) {
          return String(parseInt(item.point.percent * 100)) + "%";
        }
      });
    chart.guide().html({
      position: ["50%", "50%"],
      html: `
      <div id="g2-guide-html" style="text-align: center;">
        <p id="${this.chart.id + "title"}">项目总计</p>
        <p id="${this.chart.id + "value"}">500</p>
      </div>`
    });
    let title = this.chart.id + "title";
    let value = this.chart.id + "value";
    chart.on("interval:mouseenter", function(ev) {
      let data = ev.data._origin;
      let g2Div = document.getElementById("g2-guide-html");
      let g2Title = document.getElementById(title);
      let g2Value = document.getElementById(value);
      g2Div.style.opacity = 1;
      g2Title.innerHTML = data.type;
      g2Value.innerHTML = data.value;
    });

    chart.on("interval:mouseleave", function() {
      let g2Title = document.getElementById(title);
      let g2Value = document.getElementById(value);
      g2Title.innerHTML = "项目总计";
      g2Value.innerHTML = 500;
    });
    chart.render();
  }
};
</script>

<style lang="scss" scoped></style>
